<template>
  <div class="app-container">
    <!-- 查询表单 -->
    <el-form inline>
      <el-form-item label="模板名称">
        <el-input clearable placeholder="请输入模板名称" v-model="searchForm.templateName" style="width: 200px" />
      </el-form-item>
      <el-form-item label="模板类型">
        <el-select v-model="searchForm.type" placeholder="请选择模板类型" clearable style="width: 150px">
          <el-option label="单页" value="page" />
          <el-option label="列表页" value="list" />
          <el-option label="详情页" value="detail" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch" size="small">
          <el-icon><Search /></el-icon>
          搜索
        </el-button>
        <el-button @click="handleReset" size="small">
          <el-icon><Refresh /></el-icon>
          重置
        </el-button>
        <el-button type="primary" @click="handleAdd" size="small">
          <el-icon><Plus /></el-icon>
          新增
        </el-button>
      </el-form-item>
    </el-form>

    <!-- 表格 -->
    <BaseTable
      :table-data="templateList"
      :table-columns="tableColumns"
      :table-loading="loading"
      :page-num="pageInfo.pageNum"
      :page-size="pageInfo.pageSize"
      :total="pageInfo.total"
      :options="tableOptions"
      @update:pageNum="pageInfo.pageNum = $event"
      @update:pageSize="pageInfo.pageSize = $event"
      @turnOn="loadTemplateList"
    >
      <!-- 模板类型插槽 -->
      <template #type="{ row }">
        <el-tag :type="row.type === 'normal' ? 'primary' : 'success'">
          {{ transferType(row.type) }}
        </el-tag>
      </template>

      <!-- 模块列表插槽 -->
      <template #moduleList="{ row }">
        <span v-if="row.moduleList && row.moduleList.length > 0">
          {{ row.moduleList.join(", ") }}
        </span>
        <span v-else>--</span>
      </template>

      <!-- 创建时间插槽 -->
      <template #createdAt="{ row }">
        <span v-if="row.createdAt">
          {{ new Date(row.createdAt).toLocaleString() }}
        </span>
        <span v-else>--</span>
      </template>

      <!-- 操作插槽 -->
      <template #operation="{ row }">
        <el-button size="small" type="primary" text @click="handleEdit(row)"> 编辑 </el-button>
        <el-button size="small" type="danger" text @click="handleDelete(row)"> 删除 </el-button>
      </template>
    </BaseTable>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Search, Refresh, Plus } from "@element-plus/icons-vue";
import BaseTable from "@/components/BaseTable/index.vue";
import { getTemplateList, createTemplate, updateTemplate, deleteTemplate, batchDeleteTemplates } from "@/api/webbase";
import { useRouter } from "vue-router";

// 模板数据类型定义
interface TemplateItem {
  _id: string;
  templateName: string;
  bindFileName: string;
  bindComponentString: string;
  moduleList?: string[];
  templateContentCache?: string;
  type?: string;
  createdAt?: Date;
  updatedAt?: Date;
}

const router = useRouter();

// 查询表单
const searchForm = reactive({
  templateName: "",
  type: ""
});

// 分页信息
const pageInfo = reactive({
  pageNum: 1,
  pageSize: 20,
  total: 0
});

// 模板数据
const templateList = ref<TemplateItem[]>([]);
const loading = ref(false);

// 表格配置
const tableOptions = {
  stripe: true,
  showSelect: false,
  showOrder: true,
  showOption: true,
  optionWidth: 150
};

// 表格列配置
const tableColumns = [
  {
    prop: "templateName",
    label: "模板名称",
    width: 180
  },
  {
    prop: "bindFileName",
    label: "绑定文件名",
    width: 200,
    showOverflowTooltip: true
  },
  {
    prop: "bindComponentString",
    label: "组件字符串",
    width: 200,
    showOverflowTooltip: true
  },
  {
    prop: "type",
    label: "模板类型",
    width: 120,
    slotable: true
  },
  {
    prop: "moduleList",
    label: "包含模块",
    width: 200,
    slotable: true
  },
  {
    prop: "createdAt",
    label: "创建时间",
    width: 180,
    slotable: true
  }
];

/**
 * 分页查询模板列表
 */
const loadTemplateList = async () => {
  try {
    loading.value = true;
    const params = {
      ...searchForm,
      pageNum: pageInfo.pageNum,
      pageSize: pageInfo.pageSize
    };
    const res = await getTemplateList(params);
    if (res.data) {
      templateList.value = (res.data as { rows?: TemplateItem[]; list?: TemplateItem[] }).rows || (res.data as { rows?: TemplateItem[]; list?: TemplateItem[] }).list || [];
      pageInfo.total = ((res.data as any).total as number) || 0;
    }
    console.log("模板列表:", res.data);
  } catch (error) {
    console.error("获取模板列表失败:", error);
    ElMessage.error("获取数据失败");
  } finally {
    loading.value = false;
  }
};

/**
 * 搜索处理
 */
const handleSearch = () => {
  pageInfo.pageNum = 1;
  loadTemplateList();
};

/**
 * 重置处理
 */
const handleReset = () => {
  searchForm.templateName = "";
  searchForm.type = "";
  pageInfo.pageNum = 1;
  loadTemplateList();
};

/**
 * 新增处理
 */
const handleAdd = () => {
  router.push({ path: "/add-template" });
};

/**
 * 编辑处理
 * @param row 行数据
 */
const handleEdit = (row: TemplateItem) => {
  router.push({ path: "/add-template", query: { id: row._id } });
};

/**
 * 删除处理
 * @param row 行数据
 */
const handleDelete = (row: TemplateItem) => {
  ElMessageBox.confirm(`确定要删除模板 "${row.templateName}" 吗？`, "确认删除", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      try {
        await deleteTemplate(row._id);
        ElMessage.success("删除成功");
        loadTemplateList();
      } catch (error) {
        console.error("删除失败:", error);
        ElMessage.error("删除失败");
      }
    })
    .catch(() => {
      ElMessage.info("已取消删除");
    });
};

const transferType = (type: string) => {
  if (type === "list") {
    return "列表页";
  } else if (type === "detail") {
    return "详情页";
  } else if (type === "page") {
    return "单页";
  }
};

// 组件挂载时加载数据
onMounted(() => {
  loadTemplateList();
});
</script>

<style scoped lang="less">
.app-container {
  padding: 20px;
}
</style>
<!-- 模板管理页面 - 用于管理系统中的各种模板 -->
